package com.yexin.qingzhou.controller;

import com.yexin.qingzhou.common.Result;
import com.yexin.qingzhou.dto.ChatRequest;
import com.yexin.qingzhou.dto.ConversationDTO;
import com.yexin.qingzhou.entity.ChatMessage;
import com.yexin.qingzhou.service.ChatHistoryService;
import com.yexin.qingzhou.service.DeepSeekService;
import com.yexin.qingzhou.util.ThreadLocalUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/chat")
public class ChatController {

    private final DeepSeekService deepSeekService;
    private final ChatHistoryService chatHistoryService;
    // 用于存储所有的SSE连接
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    public ChatController(DeepSeekService deepSeekService, ChatHistoryService chatHistoryService) {
        this.deepSeekService = deepSeekService;
        this.chatHistoryService = chatHistoryService;
    }

    // 建立SSE连接
    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect() {
        // 获取用户ID
        Long userId = getUserIdFromToken();
        if (userId == null) {
            throw new RuntimeException("请先登录");
        }

        // 创建新的SSE连接
        SseEmitter emitter = new SseEmitter(-1L); // 无超时
        String emitterId = userId + "_" + System.currentTimeMillis();
        
        // 设置完成回调，移除存储的emitter
        emitter.onCompletion(() -> emitters.remove(emitterId));
        emitter.onTimeout(() -> emitters.remove(emitterId));
        
        // 存储emitter
        emitters.put(emitterId, emitter);
        
        // 发送连接成功事件
        try {
            emitter.send(SseEmitter.event()
                .name("connected")
                .data(Result.success(Map.of(
                    "message", "SSE连接已建立",
                    "emitterId", emitterId
                ))));
        } catch (IOException e) {
            emitters.remove(emitterId);
            emitter.completeWithError(e);
        }
        
        return emitter;
    }

    // 发送聊天消息
    @PostMapping("/send")
    public Result<?> sendMessage(@RequestBody ChatRequest request, 
                               @RequestParam(required = false) Long conversationId,
                               @RequestParam String emitterId) {
        // 获取用户ID
        Long userId = getUserIdFromToken();
        if (userId == null) {
            return Result.error("请先登录");
        }

        // 获取对应的emitter
        SseEmitter emitter = emitters.get(emitterId);
        if (emitter == null) {
            return Result.error("SSE连接不存在，请重新连接");
        }

        try {
            // 如果没有会话ID，创建新会话
            if (conversationId == null) {
                conversationId = chatHistoryService.createNewConversation(userId);
            }

            final Long finalConversationId = conversationId;

            // 获取历史消息
            List<ChatMessage> messages = chatHistoryService.getHistoryByConversationId(finalConversationId);
            
            // 添加用户的新消息
            ChatMessage userMessage = new ChatMessage("user", request.getMessage());
            messages.add(userMessage);
            
            // 保存用户消息
            chatHistoryService.saveChat(userId, userMessage, finalConversationId);

            // 调用DeepSeek API并处理流式响应
            deepSeekService.chatStream(messages, new DeepSeekService.StreamCallback() {
                @Override
                public void onMessage(String content) {
                    try {
                        emitter.send(SseEmitter.event()
                            .name("message")
                            .data(content));
                    } catch (IOException e) {
                        onError(e);
                    }
                }

                @Override
                public void onComplete(String fullResponse) {
                    try {
                        // 保存AI响应
                        ChatMessage assistantMessage = new ChatMessage("assistant", fullResponse);
                        chatHistoryService.saveChat(userId, assistantMessage, finalConversationId);
                        
                        // 发送完成事件
                        emitter.send(SseEmitter.event()
                            .name("complete")
                            .data(Map.of("conversationId", finalConversationId)));
                    } catch (Exception e) {
                        onError(e);
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    try {
                        emitter.send(SseEmitter.event()
                            .name("error")
                            .data(Map.of(
                                "message", throwable.getMessage(),
                                "conversationId", finalConversationId
                            )));
                    } catch (IOException e) {
                        emitter.completeWithError(e);
                    }
                }
            });

            return Result.success(Map.of("conversationId", finalConversationId));
        } catch (Exception e) {
            return Result.error("对话失败：" + e.getMessage());
        }
    }

    //获取对话历史
    @GetMapping("/conversations/{conversationId}")
    public Result<?> getConversationHistory(@PathVariable Long conversationId) {
        Long userId = getUserIdFromToken();
        if (userId == null) {
            return Result.error("请先登录");
        }
        
        List<ChatMessage> history = chatHistoryService.getHistoryByConversationId(conversationId);
        return Result.success(history);
    }

    @GetMapping("/conversations")
    public Result<?> getUserConversations() {
        Long userId = getUserIdFromToken();
        if (userId == null) {
            return Result.error("请先登录");
        }
        
        List<ConversationDTO> conversations = chatHistoryService.getUserConversations(userId);
        return Result.success(conversations);
    }

    @DeleteMapping("/conversations/{conversationId}")
    public Result<?> deleteConversation(@PathVariable Long conversationId) {
        Long userId = getUserIdFromToken();
        if (userId == null) {
            return Result.error("请先登录");
        }
        
        try {
            chatHistoryService.deleteConversation(userId, conversationId);
            return Result.success(null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    private Long getUserIdFromToken() {
        // 通过ThreadLocalUtil获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Object idObj = map.get("id");
        if (idObj == null) {
            return null;
        }
        // 处理Integer到Long的转换
        return idObj instanceof Integer ? 
               ((Integer) idObj).longValue() : 
               (Long) idObj;
    }
} 